<?php
header("Content-Type:text/html; charset=utf-8");
date_default_timezone_set('PRC');
require_once('config.php');
$conn = mysql_connect($cfg_dbhost,$cfg_dbuser,$cfg_dbpwd);
mysql_select_db($cfg_dbname,$conn);
function download($url,$path)
{
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
  $file = curl_exec($ch);
  curl_close($ch);
  $resource = fopen($path, 'a');
  fwrite($resource, $file);
  fclose($resource);
}
function randomkeys($length)   
{   
   //$pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ'; 
      $str = null;
      $strPol = "1234567890";//大小写字母以及数字
      $max = strlen($strPol)-1;
      
      for($i=0;$i<$length;$i++){
         $str.=$strPol[rand(0,$max)];
      }
      return $str;
}
function randomsku($length)   
{   
   $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';  
    for($i=0;$i<$length;$i++)   
    {   
        $key .= $pattern{mt_rand(0,35)};    //生成php随机数   
    }   
    return $key;
}
function trimd($str){
$str=str_replace("\t"," ",$str);
$str=str_replace("'","''",$str);
$str=str_replace('V',"",$str);
$str=str_replace("\r","",$str);
$str=str_replace("$","",$str);
$str=str_replace("\n","<br/>",$str);
return trim($str);
}
function ensure_writable_dir($dir) {
    if(!file_exists($dir)) {
        mkdir($dir, 0766, true);
        chmod($dir, 0766);
        chmod($dir, 0777);
    }
    else if(!is_writable($dir)) {
        chmod($dir, 0766);
        chmod($dir, 0777);
        if(!is_writable($dir)) {
            throw new FileSystemException("目录 $dir 不可写");
        }
    }
}
function rpa($str){
return substr($str,0,strlen($str)-1); 
}

$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
fwrite($myfile,$_POST["data"]);
fclose($myfile);
$data = json_decode($_POST["data"], true);
//$data = json_decode($maindata, true);
$user=trimd($_GET["u"]);
//$user="djfadmin";
//echo $user."<br/>";
$lastversion="20190110192000";
$version=$data['Version'];
$Platform=$data['Platform'];
//echo $Platform."<br/>";
$Category=trimd($data['Category']);
//echo $Category."<br/>";
$Url=trimd($data['Url']);
//echo $Url."<br/>";
$Proname=trimd($data['Proname']);
//echo $Proname."<br/>";
$Price=htmlspecialchars($data['Price']);
//echo $Price."<br/>";
$Currency=$data['Currency'];
//echo $Currency."<br/>";
$Shopname=trimd($data['Shopname']);
//echo $Shopname."<br/>";
$Sketch=trimd($data['Sketch']);
//echo $Sketch."<br/>";
$Description=trimd($data['Description']);
if(empty($Description)){$Description=$Sketch;}
//echo $Description."<br/>";
$PID=$data['PID'];
//echo $PID."<br/>";
$Images=$data['Images'];
$Attribute=$data['Attribute'];
$Products=$data['Products'];
if($lastversion!==$version){
echo "版本不匹配，当前服务器API版本：".$lastversion;
exit;
}
if(!empty($Sketch)){$content=$Sketch;}
if(!empty($Description)){$content=$Description;}

$ucalist="select * from ph_admin where admin='".$user."'";
$ucaresult=mysql_query($ucalist);
if(mysql_num_rows($ucaresult)<1){
echo "user not exist!";
exit;
}else{
$rowuser = mysql_fetch_array($ucaresult);
$ucalist2="select * from ph_admin where admin='".$rowuser["parent"]."'";
$ucaresult2=mysql_query($ucalist2);
$rowuser2 = mysql_fetch_array($ucaresult2);
if($rowuser["thetype"]=="超级管理员"||$rowuser["thetype"]=="管理员"||$rowuser2["thetype"]=="超级管理员"){
$maxhostsize=$rowuser["maxhostsize"];
$currenthostsize=$rowuser["currenthostsize"];
$uid=$rowuser["ID"];
}else{
$maxhostsize=$rowuser2["maxhostsize"];
$currenthostsize=$rowuser2["currenthostsize"];
$uid=$rowuser2["ID"];
}
}

$calist="select * from ph_bcategory where bname='".$Category."' and platform='".$Platform."' and user_name='".$user."'";
$caresult=mysql_query($calist);
if(mysql_num_rows($caresult)<1){
$sqlca = "INSERT INTO ph_bcategory(bname,platform,user_name)VALUES('".$Category."','".$Platform."','".$user."')";
mysql_query($sqlca,$conn);
}
$Arrtsname=array();
foreach ($Attribute as $key=>$Value) {
  array_push($Arrtsname,$key);
}
if(count($Arrtsname)>1){$shuxing="ColorSize";}else{$shuxing=$Arrtsname[0];}
$sql = "INSERT INTO ph_products(proname,price,saleprice,skucode,coin,code,content,ndate,bname,user_name,des,keywords,weight,kucun,btname,fromurl,shopname,platform,sketch)VALUES('".$Proname."','".$Price."','".$Price."','".randomsku(19)."','".$Currency."','".randomkeys(13)."','".trimd($content)."','".date("Y-m-d",time())."','".$Category."','".$user."','".$Description."','','1','50','".trimd($shuxing)."','".$Url."','".$Shopname."','".$Platform."','".$Sketch."')";
mysql_query($sql,$conn);
$proid=mysql_insert_id();
if(!empty($Products[0]["Images"])){
for($p=0;$p<count($Products[0]["Images"]);$p++){
    $header_array = get_headers($Products[0]["Images"][$p], true);
    $size = $header_array['Content-Length']/1024;
	if((int)($size+$currenthostsize)>$maxhostsize){
			echo "空间已满，上传失败";
			exit;
	}
  mysql_query("update ph_admin set currenthostsize=currenthostsize+".$size." where id='".$uid."'");
  $pathimgnew='files/'.$uid.'/'.date("Y-m-d",time()).'/';
	$pathimg=$pathimgnew.randomkeys(8).strtotime(date("Y-m-d H:i:s",time())).".jpg";
	ensure_writable_dir($pathimgnew);
    download($Products[0]["Images"][$p],$pathimg); 
    mysql_query("INSERT INTO ph_img(imgpath,proid,px)VALUES('/".$pathimg."','".$proid."','".$p."');",$conn);
    
}}
for($i=0;$i<count($Products);$i++){

  $sx="";
  for($r=0;$r<count($Products[$i]["Value"]);$r++){
   $sx.=$Products[$i]["Value"][$r].",";
  }
  
  mysql_query("INSERT INTO ph_shuxing(cname,proid,price,saleprice,kucun,skucode)VALUES('".trimd(rpa($sx))."','".$proid."','".trimd($Products[$i]["Price"])."','".trimd($Products[$i]["Price"])."','50','');",$conn);
    $btid=mysql_insert_id();
  if(!empty($Products[$i]["Images"])){
    for($t=0;$t<count($Products[$i]["Images"]);$t++){
    $pathimgnew='files/'.$uid.'/'.date("Y-m-d",time()).'/';
	$pathimg=$pathimgnew.randomkeys(8).strtotime(date("Y-m-d H:i:s",time())).".jpg";
	$header_array = get_headers($Products[$i]["Images"][$t], true);
    $size = $header_array['Content-Length']/1024;
	if((int)($size+$currenthostsize)>$maxhostsize){
			echo "空间已满，上传失败";
			exit;
	}
  mysql_query("update ph_admin set currenthostsize=currenthostsize+".$size." where id='".$uid."'");
    download($Products[$i]["Images"][$t],$pathimg); 
    mysql_query("INSERT INTO ph_img(imgpath,proid,px,btid)VALUES('/".$pathimg."','".$proid."','".$r."','".$btid."');",$conn);
	}
  }
  $r=$r+1;
}

for($i=0;$i<count($Images);$i++){
  $pathimgnew='files/'.$uid.'/'.date("Y-m-d",time()).'/';
	$pathimg=$pathimgnew.randomkeys(8).strtotime(date("Y-m-d H:i:s",time())).".jpg";
	$header_array = get_headers($Images[$i], true);
    $size = $header_array['Content-Length']/1024;
	if((int)($size+$currenthostsize)>$maxhostsize){
			echo "空间已满，上传失败";
			exit;
	}
  mysql_query("update ph_admin set currenthostsize=currenthostsize+".$size." where id='".$uid."'");
 download($Images[$i],$pathimg);
 mysql_query("INSERT INTO ph_img(imgpath,proid,px)VALUES('/".$pathimg."','".$proid."','".$i."');",$conn);
  }
 echo "ok";
?>